const exp = require('express');
const Crawler = require('crawler');
const cookieParser = require('cookie-parser');
const fs = require('fs');
const bodyParser = require('body-parser');
const app = exp();

app.use(exp.static('wwwroot'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.engine('html', require("express-art-template"));
app.set('view engine', 'html');

var c = new Crawler({
    maxConnections: 10,
    // This will be called for each crawled page
    callback: function (error, res, done) {
        if (error) {
            console.log(error);
        } else {
            var $ = res.$;
            var jArr = [];

            // 处理爬取到的数据，转换为对象
            $(".cate_menu_item").each(function () {

                var arr = [];
                $(this).find('.cate_menu_lk').each(function (index, item) {
                    var sorts = {};
                    var sort = $(item).text();
                    var link = $(item).attr('href');
                    if (!link.startsWith('http')) {
                        link = 'http:' + link;
                    }
                    sorts.sort = sort;
                    sorts.link = link;
                    arr.push(sorts);
                });
                // sort.sorts = arr;
                jArr.push(arr);
            })
            // writeFileSync 要转换成字符串存进去
            // console.log(jArr);
            fs.writeFileSync('./sorts.json', JSON.stringify(jArr));
        }
        done();
    }
});
c.queue('https://www.jd.com/');

app.get('/', function (req, res) {
    var data = fs.readFileSync('./jsondata/catedata.json').toString();
    var addr = fs.readFileSync('./jsondata/addr.json').toString();
    var jdms = fs.readFileSync('./jsondata/jdms.json').toString();
    var sup = fs.readFileSync('./jsondata/sup.json').toString();
    var top = fs.readFileSync('./jsondata/top.json').toString();
    var quan = fs.readFileSync('./jsondata/quan.json').toString();
    var find = fs.readFileSync('./jsondata/fineME.json').toString();
    var entry = fs.readFileSync('./jsondata/entry.json').toString();
    var gird = fs.readFileSync('./jsondata/girdItem.json').toString();
    var more = fs.readFileSync('./jsondata/moregoods.json').toString();

    var addrArr = [];
    var dataArr = [];
    var jdmsArr = [];
    var supArr = [];
    var topArr = [];
    var quanArr = [];
    var findArr = [];
    var entryArr = [];
    var girdArr = [];
    var moreArr = [];

    if (more) {
        moreArr = JSON.parse(more);
        for (var i = 0; i < moreArr.length; i++) {
            if (moreArr[i].info.length > 40) {
                moreArr[i].info = moreArr[i].info.substr(0, 36);
            }
        }
    }
    if (gird) {
        girdArr = JSON.parse(gird);
    }
    if (entry) {
        entryArr = JSON.parse(entry);
    }
    if (find) {
        findArr = JSON.parse(find);
    }
    if (quan) {
        quanArr = JSON.parse(quan);
    }
    if (top) {
        topArr = JSON.parse(top);
    }
    if (sup) {
        supArr = JSON.parse(sup);
    }
    if (addr) {
        addrArr = JSON.parse(addr);
    }
    if (jdms) {
        jdmsArr = JSON.parse(jdms);
        for (var i = 0; i < (jdmsArr[0].boxBd.item).length; i++) {
            if ((jdmsArr[0].boxBd.item)[i].text.length > 25) {
                (jdmsArr[0].boxBd.item)[i].text = (jdmsArr[0].boxBd.item)[i].text.substr(0, 25);
            }
        }
    }
    if (data) {
        dataArr = JSON.parse(data);
    }
    // 渲染页面
    res.render('index', {
        data: dataArr,
        addr: addrArr,
        jdms: jdmsArr,
        sup: supArr,
        top: topArr,
        quan: quanArr,
        find: findArr,
        entry: entryArr,
        gird: girdArr,
        more: moreArr
    })
})

app.post('/api/user/register', (req, res) => {
    var filename = `users/${req.body.userName}.txt`;
    function saveFile() {
        fs.exists(filename, (exists) => {
            if (!exists) {
                // 不存在这个文件
                fs.appendFile(filename, JSON.stringify(req.body), (error) => {
                    if (error) {
                        res.status(200).json({
                            code: 'error',
                            message: "保存信息失败"
                        })
                    } else {
                        res.status(200).json({
                            code: "success",
                            message: "注册成功"
                        })
                    }
                })
            } else {
                // 已经存在
                res.status(200).json({
                    code: "error",
                    message: "该用户已经注册"
                })
            }
        })
    }

    fs.exists('users', (exists) => {
        if (exists) {
            saveFile();
        } else {
            fs.mkdir('users', (error) => {
                if (error) {
                    res.status(200).json({
                        code: "error",
                        message: "创建文件夹失败"
                    })
                } else {
                    saveFile();
                }
            })
        }
    })
})

app.post('/api/user/login', (req, res) => {
    var filename = `users/${req.body.userName}.txt`
    fs.exists(filename, (exists) => {
        if (exists) {
            // 已经注册过了
            var user = JSON.parse(fs.readFileSync(filename).toString());
            if (req.body.password == user.userPsw) {
                // 密码正确
                res.cookie('userName', req.body.userName);
                res.status(200).json({
                    code: "success",
                    message: "登录成功"
                })
            } else {
                // 密码不正确
                res.status(200).json({
                    code: "error",
                    message: "密码错误"
                })
            }
        } else {
            // 还没有注册过
            res.status(200).json({
                code: 'error',
                message: '该用户尚未注册，请先注册'
            })
        }
    })
})

app.get('/api/user/logout',(reeq,res)=>{
    res.clearCookie('userName');
    res.redirect('/');
})

app.listen(3000, () => {
    console.log('3000...');
})